package com.logicbus.dbcp.xscript;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.anysoft.util.Settings;
import com.logicbus.dbcp.processor.Plugin;
import com.logicbus.dbcp.processor.PluginManager;
import org.apache.commons.lang3.StringUtils;

/**
 * 注册预处理器的Plugin
 */
public class PreprocessorPlugin extends AbstractLogiclet {
    protected String $name = "";
    protected String $module = "";

    public PreprocessorPlugin(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);
        $name = PropertiesConstants.getRaw(p,"name",$name);
        $module = PropertiesConstants.getRaw(p,"module",$module);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx,
                             ExecuteWatcher watcher) {
        String name = PropertiesConstants.transform(ctx,$name,"");
        String module = PropertiesConstants.transform(ctx,$module,"");
        if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(module)){
            ClassLoader cl = Settings.getClassLoader();
            cl = cl != null ? cl : Thread.currentThread().getContextClassLoader();
            Class<? extends Plugin> clazz = null;
            try {
                clazz = (Class<? extends Plugin>)cl.loadClass(module);
                PluginManager.registerPlugin(name,clazz);
            } catch (ClassNotFoundException e) {
                log("Can not find class " + module);
            }
        }
    }
}